<?php

namespace App\Admin\Forms\User;

use App\Models\TgChannelBalance;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class AssetUpdateForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $amount = floatval($input['amount'] ?? 0);
        $remark = $input['remark'] ?? "";
        $id = $this->payload["id"];
        $balance_type = $input['balance_type'] ?? "";
        /**
         * @var $user_asset TgChannelBalance
         */
        $user_asset = TgChannelBalance::query()->where('balance_id', $id)->first();
        $uid = $user_asset->channel_id;

        $type = $amount > 0 ? ASSET_DEPOSITS_SYS : ASSET_WITHDRAW_SYS;
        $op_result = $user_asset->assetChange(
            $uid,
            ASSET_SYMBOL_DEFAULT,
            $amount,
            $type,
            0,
            $balance_type
        );

        if ($op_result) {
            return $this
                ->response()
                ->success('执行成功')
                ->refresh();
        } else {
            return $this
                ->response()
                ->error('执行失败');
        }
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->text('amount', __("金额"))
            ->help("支持正负金额")
            ->required()->rules("notIn:0");

        $this->select('balance_type', __("余额类型"))->options(tt_balance_type('', true))->required();
        $this->textarea('remark', __("备注"))
            ->placeholder("系统调账");

        $this->hidden("id")->value($this->getKey());
    }

    public function default()
    {
        return [
            "amount" => 0
        ];
    }
}
